package initialization

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/zap"
	"os"
	"time"
	"vpom_-system/global"
)

func InitMongo() *mongo.Client {
	mongoCfg := global.Config.Mongo
	clientOptions := options.Client().ApplyURI(mongoCfg.Dsn()).
		SetMaxPoolSize(uint64(mongoCfg.ConnectionOptions.MaxPoolSize)).
		SetMinPoolSize(uint64(mongoCfg.ConnectionOptions.MinPoolSize)).
		SetConnectTimeout(5 * time.Second).          // 节点连接超时
		SetServerSelectionTimeout(30 * time.Second). // ✅ 关键：副本集选择超时
		SetSocketTimeout(10 * time.Second)           // 单次操作超时
	//SetReplicaSet(mongoCfg.ReplicaSet)

	if mongoCfg.SSL {
		clientOptions.SetTLSConfig(nil)
	}

	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		global.Log.Error("Failed to connect to MongoDB: %v", zap.Error(err))
		os.Exit(1)
	}
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		global.Log.Error("Failed to ping MongoDB: %v", zap.Error(err))
		os.Exit(1)
	}
	global.Log.Info("MongoDB连接成功")
	err = CreateIndexes(client)
	if err != nil {
		global.Log.Error("Failed to ping MongoDB: %v", zap.Error(err))
		os.Exit(1)
	}
	return client
}

func CreateIndexes(client *mongo.Client) error {
	collection := client.Database(global.Config.Mongo.Database).Collection("revoked_tokens")
	collection2 := client.Database(global.Config.Mongo.Database).Collection("revoked_tokens")
	// 创建 TTL 索引
	indexModel := mongo.IndexModel{
		Keys:    bson.M{"expiresAt": 1},                   // 对 expiresAt 字段创建升序索引
		Options: options.Index().SetExpireAfterSeconds(0), // 过期时间由字段值决定
	}
	// 创建索引
	_, err := collection.Indexes().CreateOne(context.Background(), indexModel)
	if err != nil {
		return err
	}
	_, err = collection2.Indexes().CreateOne(context.Background(), indexModel)
	if err != nil {
		return err
	}
	return nil
}
